<!--
使用antd原生Form生成 详细用法参考ant-design-vue Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import {computed, onMounted, ref} from 'vue';
import { renderDict } from '#/utils/render';
import { DictEnum } from '@vben/constants';
import { Input, Textarea, Select, RadioGroup, CheckboxGroup, DatePicker, Form, FormItem } from 'ant-design-vue';
import {addFullName, getPopupContainer, listToTree} from '@vben/utils';
import { pick } from 'lodash-es';

import { getDictOptions } from '#/utils/dict';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import {categoryAdd, categoryInfo, categoryList, categoryUpdate} from '#/api/category/category';
import type { CategoryForm } from '#/api/category/category/model';
import type {Dept} from "#/api/system/dept/model";
import {deptList, deptNodeList} from "#/api/system/dept";

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

/**
 * 定义默认值 用于reset
 */
const defaultValues: Partial<CategoryForm> = {
  id: undefined,
  name: undefined,
  parentId: undefined,
  orderNum: undefined,
  info: undefined,
  type: undefined,
  status: undefined,
  remark: undefined
}

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<CategoryForm>>({
    name: [
      { required: true, message: "分类名称不能为空" }
    ],
    parentId: [
      { required: true, message: "父分类ID不能为空" }
    ],
    orderNum: [
      { required: true, message: "显示顺序不能为空" }
    ],
    info: [
      { required: true, message: "描述不能为空" }
    ],
    type: [
      { required: true, message: "分类不能为空" }
    ],
    status: [
      { required: true, message: "状态不能为空" }
    ],
    remark: [
      { required: true, message: "备注不能为空" }
    ]
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[550px]',
  fullscreenButton: false,
  closeOnClickModal: false,
  onClosed: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await categoryInfo(id);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = filterRecord;
    }

    modalApi.modalLoading(false);
  },
});
// 获取所有分类数据
const parentOptions = ref<{ label: string, value:  string }[]>([]);

async function fetchParentOptions() {
  try {
    const categories = await categoryList({ parentId: 0 });
    console.log('categories',categories);
    console.log('categories.data',categories.rows);
    if (categories && categories.rows) {
      parentOptions.value = [
        { label: '无上级', value: 0 },
        ...categories.rows.map(category => ({
          label: category.name,
          value: category.id
        }))
      ];

    } else {
      console.error('No categories data found');
    }
  } catch (error) {
    console.error('Failed to fetch parent categories:', error);
  }
}

onMounted(() => {
  fetchParentOptions();
});



async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    await (isUpdate.value ? categoryUpdate(data) : categoryAdd(data));
    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  formData.value = defaultValues;
  resetFields();
}
</script>

<template>
  <BasicModal :title="title">
    <Form :label-col="{ span: 4 }">
      <FormItem label="分类名称" v-bind="validateInfos.name">
        <Input v-model:value="formData.name" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="父分类ID" v-bind="validateInfos.parentId">
        <Select
          v-model:value="formData.parentId"
          :options="parentOptions"
          :getPopupContainer="getPopupContainer"
          :placeholder="$t('ui.formRules.selectRequired')"
        />
      </FormItem>
      <FormItem label="显示顺序" v-bind="validateInfos.orderNum">
        <Input v-model:value="formData.orderNum" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="描述" v-bind="validateInfos.info">
        <Input v-model:value="formData.info" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="类型" v-bind="validateInfos.type">
        <Select
          v-model:value="formData.type"
          :options="getDictOptions('sys_category', true)"
          :getPopupContainer="getPopupContainer"
          :placeholder="$t('ui.formRules.selectRequired')"
        />
      </FormItem>
      <FormItem label="状态" v-bind="validateInfos.status">
        <RadioGroup
          button-style="solid"
          option-type="button"
          v-model:value="formData.status"
          :options="getDictOptions(DictEnum.SYS_NORMAL_DISABLE)"
        />
      </FormItem>
      <FormItem label="备注" v-bind="validateInfos.remark">
        <Textarea
          v-model:value="formData.remark"
          :placeholder="$t('ui.formRules.required')"
          :rows="4"
        />
      </FormItem>
    </Form>
  </BasicModal>
</template>

